package org.etcsoft.examples.saniker;

import java.io.File;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

public class TestViewer extends ApplicationWindow {
	
	public TestViewer() {
		super(null);
		addMenuBar();
	}
	
	protected void configureShell(Shell shell){
		super.configureShell(shell);
		shell.setText("파일탐색기");
		shell.setBounds(100, 100, 1000, 600);
		//shell.setLayout(new FillLayout());
		System.out.println(this.getMenuBarManager()); 
	}
	
	protected Control createContents(Composite parent){
		
		SashForm sash_form = new SashForm(parent, SWT.HORIZONTAL | SWT.NULL );
		
		//트리뷰
		final TreeViewer tv = new TreeViewer(sash_form);
		tv.setContentProvider(new FileTreeContentProvider());
		tv.setLabelProvider(new FileTreeLabelProvider());
		tv.setInput(File.listRoots());
		tv.setSorter(new ViewerSorter(){
			public int category(Object element){
				if(((File) element).isDirectory()){
					return 0;
				}
				return 1;
			}
		});
		
		tv.addFilter(new ViewerFilter(){
			@Override
			public boolean select(Viewer viewer, Object parentElement,Object element) {
				// TODO Auto-generated method stub
				return ((File) element).isDirectory();
			}
		});

//		PatternFilter patternFilter = new PatternFilter();
//	    final FilteredTree filter = new FilteredTree(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, patternFilter);
//	    tv = filter.getViewer();
	    
		//테이블 뷰
		final TableViewer tbv = new TableViewer(sash_form, SWT.BORDER);
		tbv.setContentProvider(new FileTableContentProvider());
		tbv.setLabelProvider(new FileTableLabelProvider());
		tbv.setSorter(new ViewerSorter(){
			public int category(Object element){
				if(((File) element).isDirectory()){
					return 0;
				}
				return 1;
			}
		});
		tbv.getTable().setHeaderVisible(true);
		tbv.getTable().setLinesVisible(true);
				
		//테이블 컬럼 정의
//		TableViewerColumn fileName = new TableViewerColumn(tbv, SWT.LEFT);
//		TableColumn column = fileName.getColumn();
//		column.setText("이름");
//		column.setWidth(200);		
//		column.setResizable(true);
//		column.setMoveable(true);
//		
//		fileName.setLabelProvider(new ColumnLabelProvider() {
//			private Map imageCache = new HashMap(11);
//			
//			@Override
//			public Image getImage(Object element) {
//				
//				ImageDescriptor descriptor = null;
//				
//			    if(((File) element).isDirectory())
//			    {
//			    	if(((File) element).getParent() == null)
//			    	{
//			    		descriptor = ImageDescriptor.createFromFile(this.getClass(), "icon/icon_ClosedDrive.gif");
//			    	} else 
//			    	{
//			    		descriptor = ImageDescriptor.createFromFile(this.getClass(), "icon/icon_ClosedFolder.gif");	
//			    	}
//			    	
//			    } else {
//			    	descriptor = ImageDescriptor.createFromFile(this.getClass(), "icon/icon_File.gif");
//			    }
//			    
//			    Image image = (Image) imageCache.get(descriptor);
//			    
//				if (image == null) {
//					image = descriptor.createImage();
//					imageCache.put(descriptor, image);
//				}
//				
//				return image;
//			}
//			
//			@Override
//			public String getText(Object element) {
//				String rtStr = null;
//				// TODO Auto-generated method stub
//				rtStr = ((File) element).getName();
//				return rtStr; 
//			}
//	    });
//		
//		fileName.setEditingSupport(new fileNameEditingSupport(tbv));

		final String[] COLUMN_PROPERTY = new String[] {"이름", "최종수정일자", "크기"};
		
		//테이블 컬럼정의 
		TableColumn column = new TableColumn(tbv.getTable(), SWT.LEFT);
		column.setText(COLUMN_PROPERTY[0]);
		column.setWidth(200);
        column.setResizable(true);
		column.setMoveable(true);
		
		TableColumn column1 = new TableColumn(tbv.getTable(), SWT.LEFT);
		column1.setText(COLUMN_PROPERTY[1]);
		column1.setWidth(200);
		column1.setResizable(true);
		column1.setMoveable(true);
		
		TableColumn column2 = new TableColumn(tbv.getTable(), SWT.RIGHT);
		column2.setText(COLUMN_PROPERTY[2]);
		column2.setWidth(100);
		column2.setResizable(true);
		column2.setMoveable(true);

		/*********************************************
		 * 이벤트
		 *********************************************/
		//셀에디터 기능
		tbv.setCellModifier(new ICellModifier() {

			public boolean canModify(Object element, String property) {
				return true;
			}
			
			public Object getValue(Object element, String property) {
				return ((File) element).getName();
			}
			
			public void modify(Object element, String property, Object value) {
				//이름일때만 변경
			    if( COLUMN_PROPERTY[0].equals( property ) ) {
			    	TableItem tableItem = (TableItem)element;
			    	System.out.println(tableItem.getData());
			    	File orgFile = ((File) tableItem.getData());
			    	orgFile.renameTo(new File(String.valueOf(orgFile.getParent() + value)));
				}

			    tbv.setCellEditors(new CellEditor[] {null, null, null });
			    tbv.refresh();
			}
		});
		
		//tbv.setCellEditors(new CellEditor[] { new TextCellEditor(tbv.getTable()), null, null });
		tbv.setCellEditors(new CellEditor[] { null, null, null });
		tbv.setColumnProperties(COLUMN_PROPERTY);

		//사이즈 비율 조정
		sash_form.setWeights(new int[] { 30, 70 });
		 	
		//트리뷰 선택 이벤트
		tv.addSelectionChangedListener(new ISelectionChangedListener()
		{
			public void selectionChanged(SelectionChangedEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				Object selected_file = selection.getFirstElement();
				tbv.setInput(selected_file);
			}
		});
		
		//키보드이벤트
		tv.getTree().addKeyListener(new KeyListener(){
			   public void keyPressed(KeyEvent e) {
			       //컨트롤 +N
			       if ((e.stateMask & SWT.CTRL) == SWT.CTRL && e.keyCode == 110)
			       {
			    	   //tbv.refresh();
			    	   System.out.println("Detected CTRL+N key");
			           // set table viewer selection
			           DirectoryDialog dialog = new DirectoryDialog(getShell());
			           dialog.setMessage("Choose a save directory");
			           String saveTarget = dialog.open();
			       }
			   }

			@Override
			public void keyReleased(KeyEvent e) {
			}}
		);
		
		//테이블뷰 더블클릭 이벤트
		tbv.addDoubleClickListener(new IDoubleClickListener()
		{
			@Override
			public void doubleClick(DoubleClickEvent event) {
				IStructuredSelection selection = (IStructuredSelection) event.getSelection();
				Object selected_file = selection.getFirstElement();
				//트리뷰 변경
				if(((File) selected_file).isDirectory()) {
					tv.expandToLevel(selected_file, 1);
					tbv.setInput(selected_file);
				}
			}
		});	
		
		//키보드이벤트
		tbv.getTable().addKeyListener(new KeyListener(){
		   public void keyPressed(KeyEvent e) {
		       //컨트롤 +N
		       if ((e.stateMask & SWT.CTRL) == SWT.CTRL && e.keyCode == 110)
		       {
		    	   //tbv.refresh();
		           System.out.println("Detected CTRL+N key");
		           // set table viewer selection
		           DirectoryDialog dialog = new DirectoryDialog(getShell());
		           dialog.setMessage("Choose a save directory");
		           String saveTarget = dialog.open();
		           if(saveTarget != null)
		           {
		           }
		       } 
		       else if (e.keyCode == SWT.F2){
		    	   System.out.println("Detected F2 key");
		    	   tbv.setCellEditors(new CellEditor[] { new TextCellEditor(tbv.getTable()), null, null });
		    	   
//		    	   IStructuredSelection selection = (IStructuredSelection) tbv.getSelection();
//		    	   tbv.setSelection(selection, true);
//		    	   tbv.getTable().setFocus();		    	   
		       }
		   }

			@Override
			public void keyReleased(KeyEvent e) {

			}}
		);
//		TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(tbv, new FocusCellOwnerDrawHighlighter(tbv));
//		
//		ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tbv) {
//			protected boolean isEditorActivationEvent(
//			ColumnViewerEditorActivationEvent event) {
//			return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
//				|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
//				|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.F2)
//				|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
//				|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode > 31 && event.keyCode < 127) 
//				|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
//			}
//		};
//		
//		TableViewerEditor.create(tbv, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
//				                                                   |ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
//				                                                   |ColumnViewerEditor.TABBING_VERTICAL
//				                                                   |ColumnViewerEditor.KEYBOARD_ACTIVATION);
//		
		//parent.pack();
		return parent;
	}
	
	@Override
	protected MenuManager createMenuManager() { 		
		MenuManager bar_menu = new MenuManager(""); 
		MenuManager file_menu = new MenuManager("&File"); 
//		MenuManager edit_menu = new MenuManager("&Edit"); 
//		MenuManager view_menu = new MenuManager("&View"); 
		bar_menu.add(file_menu); 
//		bar_menu.add(edit_menu); 
//		bar_menu.add(view_menu); 

		file_menu.add(new ExitAction(this)); 

		return bar_menu;
	}	
	
	class ExitAction extends Action {
		ApplicationWindow window;
		
		public ExitAction(ApplicationWindow w) {
			window = w;
			setText("E&xit@Ctrl+X");
			setToolTipText("Exit the application");
		}
		@Override
		public void run() {
			window.close();
		}
	}
	
//	private void createColumns(final Composite parent, final TableViewer viewer) {
//	    String[] titles = { "이름", "최종수정일자", "크기" };
//	    int[] bounds = { 200, 200, 100 };
//
//	    // First column is for the first name
//	    TableViewerColumn col = createTableViewerColumn(titles[0], bounds[0], 0, viewer);
//	    col.setLabelProvider(new CellLabelProvider() {
//		      @Override
//		      public void update(ViewerCell cell) {
//		        cell.setText(((File) cell.getElement()).getName());
//		      }
//		    });
//	    
//	    col.setEditingSupport(new fileNameEditingSupport(viewer));
//
//	    // Second column is for the last name
//	    col = createTableViewerColumn(titles[1], bounds[1], 1, viewer);
//	    col.setLabelProvider(new CellLabelProvider() {
//	      @Override
//	      public void update(ViewerCell cell) {
//	        cell.setText(((Person) cell.getElement()).getLastName());
//	      }
//	    });
//	    col.setEditingSupport(new LastNameEditingSupport(viewer));
//
//	    // now the gender
//	    col = createTableViewerColumn(titles[2], bounds[2], 2, viewer);
//	    col.setLabelProvider(new ColumnLabelProvider() {
//	      @Override
//	      public String getText(Object element) {
//	        Person p = (Person) element;
//	        return p.getGender();
//	      }
//	    });
//	    col.setEditingSupport(new GenderEditingSupport(viewer));
//
//
//
//	  }
//
//	private TableViewerColumn createTableViewerColumn(String title, int bound, final int colNumber, final TableViewer viewer) {
//	  final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE);
//	  final TableColumn column = viewerColumn.getColumn();
//	  column.setText(title);
//	  column.setWidth(bound);
//	  column.setResizable(true);
//	  column.setMoveable(true);
//	  return viewerColumn;
//	}

	  
	public static void main(String[] args) {
		TestViewer viewer = new TestViewer();
		viewer.setBlockOnOpen(true);
		viewer.open();
		Display.getCurrent().dispose();
	}

}
